<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { GetData, PatchModifySort, PatchModifyType } from '@/api/modules/signintask'
import GetCacheData from '@/store/modules/NewPageCache'

const imgDomain = 'https://img1.eprhan.cc'
const router = useRouter()
const cacheData = GetCacheData()

let PageNum = cacheData.GetCacheData('signintask').currentPage
const loading = ref(true)
const total = ref(0)

const taskTypeObj: { [key: number]: string } = {
  1: '连续签到送券',
  2: '邀请好友签到',
  // 3: '加福利管企微好友',
  // 4: '订阅消息提醒',
}
const findFrom = ref({
  ...(cacheData.GetCacheData('signintask').fromData),
})
const dataList: any = reactive({
  list: [],
})

async function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  const params = {
    PageIndex,
    PageSize,
    ...(findFrom.value.Title && ({ Title: findFrom.value.Title })),
    ...(findFrom.value.TaskType !== '~' && ({ TaskType: findFrom.value.TaskType })),
    ...(findFrom.value.TaskStatus !== '~' && ({ TaskStatus: findFrom.value.TaskStatus })),
  }
  await GetData(params).then(async (dataRes: any) => {
    if (dataRes.succeeded) {
      dataList.list = dataRes.data.items
      total.value = dataRes.data.total
      loading.value = false
    }
  })
  loading.value = false
}

// 查询
function Inquire() {
  GetDataList(1, cacheData.GetCacheData('signintask').currentSize)
  cacheData.SetCacheData('signintask', PageNum, cacheData.GetCacheData('signintask').currentSize, findFrom.value)
}

// 修改状态
async function ModifyType(params: any) {
  await PatchModifyType(params).then((res: any) => {
    if (res.statusCode === 200) {
      ElMessage.success('修改成功')
    }
    else {
      ElMessage.error(`修改失败。${res.errors}`)
    }
  })
}

function SortModification(message: any) {
  const params = {
    id: message.id,
    sort: message.sort,
  }
  PatchModifySort(params).then((res) => {
    if (res.data) {
      ElMessage.success('修改成功。')
    }
    else {
      ElMessage.error('修改失败。')
      GetDataList()
    }
  })
}

// 添加
function AddData() {
  router.push({
    name: 'signintaskDetail',
  })
}
// 编辑
function EditData(id: number) {
  router.push({
    name: 'signintaskDetail',
    query: {
      id,
    },
  })
}

// 翻页
function handleSizeChange(val: number) {
  GetDataList(1, val)
  cacheData.SetCacheData('signintask', PageNum, val)
}
function handleCurrentChange(val: number) {
  GetDataList(val, cacheData.GetCacheData('signintask').currentSize)
  cacheData.SetCacheData('signintask', val, cacheData.GetCacheData('signintask').currentSize)
  PageNum = val
}

const nowPageNum = computed(() => {
  return cacheData.GetCacheData('signintask').currentPage || 1
})

onMounted(async () => {
  GetDataList(PageNum, cacheData.GetCacheData('signintask').currentSize)
})
</script>

<template>
  <div>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="header">
          <el-form label-positio="right" label-width="auto">
            <div class="from">
              <el-form-item label="任务标题">
                <el-input v-model="findFrom.Title" placeholder="请输入任务标题" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="任务类型">
                <el-select v-model="findFrom.TaskType" placeholder="请选择" clearable>
                  <el-option label="全部" value="~" />
                  <el-option v-for="(item, key) in taskTypeObj" :key="key" :label="item" :value="key" />
                </el-select>
              </el-form-item>
              <el-form-item label="任务状态">
                <el-select v-model="findFrom.TaskStatus" placeholder="请选择" clearable>
                  <el-option label="全部" value="~" />
                  <el-option label="启用" value="1" />
                  <el-option label="停用" value="-1" />
                </el-select>
              </el-form-item>
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="Inquire">
              查询
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <div class="mb-5 text-right">
        <el-button type="success" @click="AddData">
          添加
        </el-button>
      </div>
      <el-table v-loading="loading" :data="dataList.list" stripe style="width: 100%;" border>
        <el-table-column align="center" prop="id" label="任务ID" width="100" />
        <el-table-column header-align="center" prop="title" label="任务标题" width="240" />
        <el-table-column align="center" label="任务图标" width="120">
          <template #default="scope">
            <el-avatar shape="square" :size="60" :src="imgDomain + scope.row.pic" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="任务类型" width="120">
          <template #default="scope">
            <el-tag>
              {{ taskTypeObj[scope.row.taskType] ? taskTypeObj[scope.row.taskType] : '未知' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="taskDesp" label="任务描述" width="160" />
        <el-table-column align="center" prop="awardDesp" label="奖励描述" width="300" />
        <el-table-column align="center" prop="awardScore" label="奖励积分" width="100" />
        <el-table-column align="center" label="连续签到天数" width="150">
          <template #default="scope">
            {{ scope.row.taskType === 1 ? scope.row.signDays : '无' }}
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="企微二维码" width="150">
          <template #default="scope">
            <el-avatar v-if="scope.row.taskType === 3" shape="square" :size="60" :src="imgDomain + scope.row.qvcodePic" />
            <span v-else>
              无
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="模板ID" width="150">
          <template #default="scope">
            {{ scope.row.taskType === 4 ? scope.row.templateIds : '无' }}
          </template>
        </el-table-column> -->
        <el-table-column align="center" prop="addTime" label="添加时间" width="200" />
        <el-table-column align="center" prop="updateTime" label="修改时间" width="200" />
        <el-table-column align="center" fixed="right" label="是否启用" width="120">
          <template #default="scope">
            <el-switch
              v-model="scope.row.taskStatus"
              :active-value="1"
              :inactive-value="-1"
              @click="ModifyType({ id: scope.row.id, enable: scope.row.taskStatus === 1 ? true : false })"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="sort" fixed="right" label="排序" width="160">
          <template #default="scope">
            <el-input v-model="scope.row.sort" style="width: 120px;">
              <template #append>
                <el-button type="primary" size="small" @click="SortModification(scope.row)">
                  修改
                </el-button>
              </template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" fixed="right" width="120">
          <template #default="scope">
            <el-button type="primary" @click="EditData(scope.row.id)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="cacheData.GetCacheData('signintask').currentSize"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="total"
        :default-current-page="nowPageNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </PageMain>
  </div>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;

    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.scrollbar-flex-content {
  display: flex;
  max-width: 300px;

  .scrollbar-flex-img {
    display: flex;
    flex-shrink: 0;
    align-items: center;
    justify-content: center;
    width: auto;
    height: 120px;
    margin-right: 10px;
  }
}
</style>
